<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use App\Http\Requests\AdminsCreateRequest;
use App\Http\Requests\ChangePasswordRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use App\Models\Admins;
use App\Models\Role;
use DB;

class AdminsController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $role = Role::select(DB::raw('id as value, display_name as name'))->get();
        return view('admin.admins.index', compact('role'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.test.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(AdminsCreateRequest $request)
    {

        $data = $request->except(['userRole','password_confirmation','_token']);
        $data['password'] = bcrypt($data['password']);

        if ($admins = Admins::create($data)) {
            if($request->get('userRole')){
                $roles = explode(',',$request->get('userRole'));
                if ($roles)   $admins->syncRoles($roles);
            }
            return response()->json(['code' => 0, 'msg' => '添加用户成功']);
        }
        return response()->json(['code' => 1, 'msg' => '系统错误']);
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $admins = Admins::findOrFail($id);
        return view('admin.admins.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $id = (int)$request->get('id');
        $admins = Admins::findOrFail($id);
        $data = [];

        DB::beginTransaction();

        //try{
            //检查是否存在昵称
            $isNickname = Admins::where('nickName', $request->get('nickName'))->where('id', '!=', $id)->count();
            if ($isNickname) return response()->json(['code' => 1, 'msg' => '昵称已存在!']);
            if ($request->get('nickname') && !$isNickname) {
                $data['nickName'] = $request->get('nickName');
            }


       

            //检查是否存在用户名 
            $isNickName = Admins::where('username', $request->get('username'))->where('id', '!=', $id)->count();
            if ($isNickName) return response()->json(['code' => 1, 'msg' => '用户名已存在!']);
            if ($request->get('username') && !$isNickName) {
                $data['username'] = $request->get('username');
            }

            if($request->get('userRole')){
                $roles = explode(',',$request->get('userRole'));
                if ($roles)   $admins->syncRoles($roles);
            }
            if ($admins->update($data)) {
                DB::commit();
                return response()->json(['code' => 0, 'msg' => '更新成功']);
            }

        //}catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => 1, 'msg' => '更新失败']);
        //}
    }




    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');

        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        if (Admins::destroy($ids)) {
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        }
        return response()->json(['code' => 1, 'msg' => '删除失败']);
    }

    /**
     * 分配角色
     */
    public function role(Request $request, $id)
    {
        $admins = Admins::findOrFail($id);
        $roles = Role::get();
        $hasRoles = $admins->roles();
        foreach ($roles as $role) {
            $role->own = $admins->hasRole($role) ? true : false;
        }
        return view('admin.admins.role', compact('roles', 'user'));
    }

    /**
     * 更新分配角色
     */
    public function assignRole(Request $request, $id)
    {
        $admins = Admins::findOrFail($id);
        $roles = $request->get('roles', []);
        if ($user->syncRoles($roles)) {
            return redirect()->to(route('admin.admins'))->with(['status' => '更新用户角色成功']);
        }
        return redirect()->to(route('admin.admins'))->withErrors('系统错误');
    }

    /**
     * 分配权限
     */
    public function permission(Request $request, $id)
    {
        $admins = Admins::findOrFail($id);
        $permissions = $this->tree();
        foreach ($permissions as $key1 => $item1) {
            $permissions[$key1]['own'] = $admins->hasDirectPermission($item1['id']) ? 'checked' : false;
            if (isset($item1['_child'])) {
                foreach ($item1['_child'] as $key2 => $item2) {
                    $permissions[$key1]['_child'][$key2]['own'] = $admins->hasDirectPermission($item2['id']) ? 'checked' : false;
                    if (isset($item2['_child'])) {
                        foreach ($item2['_child'] as $key3 => $item3) {
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $admins->hasDirectPermission($item3['id']) ? 'checked' : false;
                        }
                    }
                }
            }
        }
        return view('admin.admins.permission', compact('user', 'permissions'));
    }

    /**
     * 存储权限
     */
    public function assignPermission(Request $request, $id)
    {
        $admins = Admins::findOrFail($id);
        $permissions = $request->get('permissions');

        if (empty($permissions)) {
            $admins->permissions()->detach();
            return redirect()->to(route('admin.admins'))->with(['status' => '已更新用户直接权限']);
        }
        $admins->syncPermissions($permissions);
        return redirect()->to(route('admin.admins'))->with(['status' => '已更新用户直接权限']);
    }

    /**
     * 更改密码
     * @return \Illuminate\Contracts\View\View
     */
    public function changeMyPasswordForm()
    {
        return View::make('admin.admins.changeMyPassword');
    }

    /**
     * 用户中心
     * @return \Illuminate\Contracts\View\View
     */
    public function info()
    {
	    $admins = Auth::user();
        return View::make('admin.admins.info',compact('user'));
    }




    /**
     * 修改密码
     * @param ChangePasswordRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function changeMyPassword(ChangePasswordRequest $request)
    {
	 
        $data = $request->all(['old_password', 'new_password']);
        //验证原密码
        if (!Hash::check($data['old_password'], $request->user()->getAuthPassword())) {
          
			return response()->json(['code' => 1, 'msg' => '原密码不正确']);
        }

        try {
            $request->user()->fill(['password' => bcrypt($data['new_password'])])->save();
			//return response()->json(['code' => 0, 'msg' => '密码修改成功']);
			return Redirect::to(URL::route('admin.admins.changePassword'))->with(['success' => '密码修改成功']);
        } catch (\Exception $exception) {
			return response()->json(['code' => 1, 'msg' => '修改失败']);
        }
    }


}
